﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class Pages_RouteEdit : System.Web.UI.Page
{
	Int64 Route_id { get { return DS.ToInt64(Request.QueryString["Id"]); } }

	#region RouteStationWork
	IList<RouteStationM2M> RouteStationCollection
	{
		get
		{
			IList<RouteStationM2M> rsm2m = (Session["RouteStationCollection"] as IList<RouteStationM2M>) ?? new List<RouteStationM2M>();
			IList<RouteStationM2M> result = new List<RouteStationM2M>();
			foreach (RouteStationM2M item in rsm2m)
				if (item.x)
					result.Add(item);
			return result;
		}
		set
		{
			Session["RouteStationCollection"] = value;
		}
	}

	private void AddRouteStation (RouteStationM2M rs)
	{
		rs.x = true;
		if (rs.Distance == 0)
			rs.Distance = 1;
		IList<RouteStationM2M> rsc = RouteStationCollection;
		rsc.Add(rs);
		RouteStationCollection = rsc;
	}

	private void RemoveRouteStation (Int64 Station_id)
	{
		IList<RouteStationM2M> rsc = RouteStationCollection;
		for (int i = 0; i < rsc.Count; i++)
			if (rsc[i].Station_id == Station_id)
			{
				rsc[i].x = false;
				break;
			}
	}

	private bool SaveRouteStation(Int64 route_id)
	{
		IList<RouteStationM2M> rsc = (Session["RouteStationCollection"] as IList<RouteStationM2M>) 
										?? new List<RouteStationM2M>();
		bool result = true;
		foreach (RouteStationM2M routeStation in rsc)
		{
			routeStation.route.Id = route_id;
			result = routeStation.Merge() && result;
		}
		return result;
	}
	#endregion

	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			Session["RouteStationCollection"] = null;
			if ((Session["RouteSaved"] ?? string.Empty).ToString() == "SavedGood")
			{
				lbMessage.ForeColor = Color.Green;
				lbMessage.Text = "Данные сохранены успешно";
				Session["RouteSaved"] = null;
			}
			if (Route_id > 0)
				InitUpdateContext();
		}
	}

	private void InitUpdateContext()
	{
		Route r = DBEntity<Route>.Load(Route_id);
		if (r == null)
			Response.Redirect("~/");
		lbSourceStation.Text = r.SourceStation.Name.ToString();
		hfSourceStation.Value = r.SourceStation_id.ToString();
		lbTargetStation.Text = r.TargetStation.Name.ToString();
		hfTargetStation.Value = r.TargetStation_id.ToString();
		tbRouteName.Text = r.Name;
		aRouteEditStations.Visible = true;
		aRouteEditStations.HRef += string.Format("?Id={0}", r.Id);
		RouteStationM2M rsM2M = new RouteStationM2M();
		rsM2M.route.Id = Route_id;
		RouteStationCollection = DBEntity<RouteStationM2M>.Select(rsM2M);
		rptRouteStation.DataSource = RouteStationCollection;
		rptRouteStation.DataBind();
	}

	protected void OnRouteSave(object s, EventArgs e)
	{
		Route r = DBEntity<Route>.Load(Route_id) ?? new Route();
		r.SourceStation.Id = DS.ToInt64(hfSourceStation.Value);
		r.TargetStation.Id = DS.ToInt64(hfTargetStation.Value);
		r.Name = tbRouteName.Text;
		lbMessage.Text = string.Empty;
		if (r.SourceStation_id == 0)
			lbMessage.Text += "Не указана станция отправления<br />";
		if (r.TargetStation_id == 0)
			lbMessage.Text += "Не указана станция назначения<br />";
		if (!string.IsNullOrEmpty(lbMessage.Text) || !IsValid)
		{
			lbMessage.ForeColor = Color.Red;
			return;
		}
		if (r.Merge() && SaveRouteStation(r.Id))
		{
			if (Route_id == 0)
			{
				Session["RouteSaved"] = "SavedGood";
				Response.Redirect("~/Pages/Carrier/RouteEdit.aspx?Id=" + r.Id.ToString());
			}
			else
			{
				lbMessage.ForeColor = Color.Green;
				lbMessage.Text = "Данные сохранены успешно";
			}
		}
		else
		{
			lbMessage.ForeColor = Color.Red;
			lbMessage.Text = "При сохранении данных произошла ошибка";
		}
	}

	protected void OnCancel(object s, EventArgs e)
	{
		Response.Redirect("~/Pages/Carrier/Route.aspx");
	}

	protected void OnEditStation(object s, EventArgs e)
	{
		hfModalAction.Value = (s as LinkButton).CommandName;
		tbSearchStation.Text = string.Empty;
		rptStation.DataSource = null;
		rptStation.DataBind();
		lkbAddNewStation.Visible = false;
		MPE.Show();
	}

	protected void OnSearchStation(object s, EventArgs e)
	{
		Station station = new Station();
		station.Name = tbSearchStation.Text;
		rptStation.DataSource = DBEntity<Station>.Find(station);
		lkbAddNewStation.Visible = ((rptStation.DataSource as IList<Station>).Count == 0);
		rptStation.DataBind();
	}

	protected void OnUpdateRoute(Station s)
	{
		if (hfModalAction.Value == "SourceStation")
		{
			lbSourceStation.Text = s.Name;
			hfSourceStation.Value = s.Id.ToString();
			upRoute.Update();
		}
		if (hfModalAction.Value == "TargetStation")
		{
			lbTargetStation.Text = s.Name;
			hfTargetStation.Value = s.Id.ToString();
			upRoute.Update();
		}
		if (hfModalAction.Value == "RouteStation")
		{
			RouteStationM2M rs = new RouteStationM2M();
			rs.station.Id = s.Id;
			rs.station.Name = s.Name;
			AddRouteStation(rs);
			rptRouteStation.DataSource = RouteStationCollection;
			rptRouteStation.DataBind();
			upRoute.Update();
		}
	}

	protected void OnAddNewStation(object s, EventArgs e)
	{
		Station station = new Station();
		station.Name = tbSearchStation.Text;
		if (station.Merge())
			OnUpdateRoute(station);
	}

	protected void AddStation(object s, EventArgs e)
	{
		Station station = DBEntity<Station>.Load(DS.ToInt64((s as LinkButton).CommandArgument));
		if (station != null)
			OnUpdateRoute(station);
	}

	protected void OnDeleteStation(object s, EventArgs e)
	{
		RemoveRouteStation(DS.ToInt64((s as LinkButton).CommandArgument));
		rptRouteStation.DataSource = RouteStationCollection;
		rptRouteStation.DataBind();
		upRoute.Update();
	}
}
